const express = require('express');
const router = express.Router();
const {Chapter,Course} = require('../../models');
//const {Op} = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { Success, failure } = require('../../utils/responses');

//获取所有章节列表
router.get('/', async (req, res) => {
    try {
        const query = req.query;
        //分页查询需要的参数
        const currentPage = Math.abs(query.currentPage) || 1;
        const pageSize = Math.abs(query.pageSize) || 10;
        const offset = (currentPage - 1) * pageSize;
        if(!query.courseId){
            throw new Error('获取章节列表失败，课程ID不能为空');
        }
        const condition = {
            ...getCondition(),
            order: [['rank','ASC'],['id','ASC']],
            offset: offset,
            limit: pageSize
        };
        // condition.where={
        //     courseId:{
        //         [Op.eq]:query.courseId
        //     }
        // };
        condition.where={
            courseId:query.courseId
        }
        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`
                }
            };
        }


        const chapters = await Chapter.findAndCountAll(condition);
        Success(res, '章节查询成功', {
            rows: chapters.rows,
            pagination: {
                total: chapters.count,
                currentPage: currentPage,
                pageSize: pageSize
            }
        });
    } catch (err) {
        failure(res, err);
    }
});
//获取指定章节
router.get('/:id', async (req, res) => {
    try {

        const chapter = await GetChapter(req);
        Success(res, '获取章节成功', chapter);
    } catch (err) {
        failure(res, err);
    }
});
//创建章节
router.post('/', async (req, res) => {
    try {

        //白名单过滤
        const body = FilterBody(req);
        const chapter = await Chapter.create(body);

        Success(res, '创建章节成功', chapter, 201);
    } catch (error) {
        console.log("错误信息：", error);

        failure(res, error);

    }
});
//更新章节
router.put('/:id', async (req, res) => {
    try {
        const chapter = await GetChapter(req);
        await chapter.update(req.body);
        Success(res, '更新成功！', chapter, 200)
    } catch (err) {
        failure(res, err);
    }
});

//删除章节
router.delete('/:id', async (req, res) => {
    try {
        const chapter = await GetChapter(req);
        await chapter.destroy();
        Success(res, '删除成功');

    } catch (err) {
        failure(res, err);
    }
});


/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{rank: (number|*), video: (string|boolean|MediaTrackConstraints|VideoConfiguration|*), title, courseId: (number|*), content}}
 */
function filterBody(req) {
    return {
        courseId: req.body.courseId,
        title: req.body.title,
        content: req.body.content,
        video: req.body.video,
        rank: req.body.rank
    };
}


//获取chapter对象
async function GetChapter(req) {
    const {id} = req.params;
    console.log(id);
    const condition = getCondition();
    const chapter = await Chapter.findByPk(id,condition);
    if (!chapter) {
        throw new NotFoundError(`ID:${id}的章节未找到`);
    }
    return chapter;
}

//公共关联查询条件
function getCondition(){
    return{
        attributes:{exclude:['CourseId']},
        include:[
            {
                model:Course,
                as: 'course',
                attributes:['id','name']
            }
        ]
    }
}
module.exports = router;